package com.oocl.o2o.client.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.oocl.o2o.client.entity.Customer;
import com.oocl.o2o.client.entity.OrderItem;
import com.oocl.o2o.client.service.CustomerService;
import com.oocl.o2o.client.vo.CustomerVO;
import com.oocl.o2o.client.vo.OrderItemVO;

@Controller
public class CustomerController {
	
	@Resource
	private CustomerService customerService;
	
	//前台校验要做足：必须写  username and password
	@GetMapping("/customer")
	public String login(CustomerVO customerVO, HttpSession session){
		System.out.println("接收到的 customerVO 信息为： "+customerVO.toString());
		Customer customer = customerService.findByCustomerNameAndPassword(customerVO.getUsername(), customerVO.getPassword());
		if(customer == null){
			System.out.println("用户不存在");
			return "redirect: login";
		}else{
			
			System.out.println("登录成功");
			//存 customer
			session.setAttribute("customer", customer);
			//购物车信息
			Map<String, OrderItem> orderItems = new HashMap<String, OrderItem>();
			session.setAttribute("orderItems", orderItems);
			session.setAttribute("orderItemsSize", orderItems.size());
			//加载广告
			return "redirect: home";
		}
	}
	
	@PostMapping("/customer")
	public String register(CustomerVO customerVO){
		System.out.println("接收到的 customerVO 信息为： "+customerVO.toString());
		Customer customer = customerService.findByCustomerName(customerVO.getUsername());
		if(customer == null){ //用户之前不存在
			customer = new Customer(customerVO.getUsername(), customerVO.getPassword());
			customerService.add(customer);
			return "redirect: login";
		}else{
			return "redirect: home";
		}
	}
	
	@ResponseBody
	@GetMapping("/all")
	public String getOrderItemsSize(HttpSession session){
		Map<String, OrderItemVO> orderItems = (Map<String, OrderItemVO>) session.getAttribute("orderItems");
		if(orderItems == null || orderItems.size() == 0){
			return "no";
		}
		return "yes";
	}
	
	

}
